<template>
  <div>
    <!-- -----------------------------------------------------基本信息-------------------------------------------------------------- -->
    <el-divider>基本信息</el-divider>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" inline class="rule_form">

      <div class="dialog_left">

        <el-form-item label="采购标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入采购标题" />
        </el-form-item>

        <el-form-item label="采购品类" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择采购品类" @change="handleOptions">
            <el-option v-for="item, i in ['设备采购', '物料采购']" :label="item" :value="i" :key="i" />
          </el-select>
        </el-form-item>

        <el-form-item label="期望供货日期" prop="desiredDeliveryTime">
          <el-date-picker type="date" placeholder="请选择供货日期" :picker-options="pickerOptions"
            v-model="ruleForm.desiredDeliveryTime" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>

        <el-form-item label="购置理由" prop="reason">
          <el-input v-model="ruleForm.reason" placeholder="请输入购置理由" />
        </el-form-item>

        <el-form-item label="采购类型" prop="purchaseType">
          <el-select v-model="ruleForm.purchaseType" placeholder="请选择采购类型" @change="handleOptions">
            <el-option v-for="item, i in ['常规采购', '比价采购']" :label="item" :value="i" :key="i" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </div>
      <el-divider>采购信息</el-divider>

      <!-- -----------------------------------------------------添加采购品【按钮】-------------------------------------------------------------- -->
      <div class="dialog_btn">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddPurchase">添加采购品</el-button>
      </div>

      <div v-if="ruleForm.purchaseType == 0">
        <!-- ---------------------------------------------------常规采购：物料采购表格----------------------------------------------------------- -->
        <div class="dialog_table">
          <el-table :data="ruleForm.SubmitSelectList" max-height="550px" style="width: 100%" v-if="ruleForm.type == 1">
            <el-table-column label="序号" width="100">
              <template slot-scope="scope">
                <div> {{ scope.$index + 1 }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="materialNum" label="物料编号" width="160" />
            <el-table-column prop="materialName" label="物料名称" />
            <el-table-column prop="typeName" label="物料类别" />
            <el-table-column prop="model" label="物料规格型号" show-overflow-tooltip>
              <template slot-scope="{row}">
                <div> {{ row.model || '-' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="supplierName" label="物料供应商" show-overflow-tooltip />
            <el-table-column prop="unitName" label="物料单位" key="unitName" />
            <el-table-column label="物料类型" key="kind">
              <template slot-scope="{row}">
                <dict-tags :options="SparePartsAndConsumables" :value="row.kind" />
              </template>
            </el-table-column>
            <!-- <el-table-column prop="avgPrice" label="物料参考单价（元）" /> -->
            <el-table-column label="采购单价（元）" key="price">
              <template slot-scope="scope">
                <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.price'" :rules="rules.fileType">
                  <el-input-number style="width:100%;margin-top: 20px;" :min="0" :controls="false"
                    @input.native="onInput0_100" v-model="scope.row.price" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="采购数量" key="overplusAmount">
              <template slot-scope="scope">
                <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.overplusAmount'" :rules="rules.fileNum">
                  <el-input-number style="width:100%;margin-top: 20px;" :min="1" :controls="false"
                    @input.native="onInput0_100" v-model="scope.row.overplusAmount" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="物料总库存" key="amount">
              <template slot-scope="{row}">
                <div> {{ row.amount || '0' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="操作" width="220" fixed="right">
              <template slot-scope="scope">
                <el-button size="small" icon="el-icon-delete" type="danger" @click="handledelete(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- ---------------------------------------------------常规采购：设备采购表格----------------------------------------------------------- -->
        <div class="dialog_table">
          <el-table :data="ruleForm.SubmitSelectList" style="width: 100%" max-height="550px" v-if="ruleForm.type == 0">
            <el-table-column label="序号" width="100">
              <template slot-scope="scope">
                <div> {{ scope.$index + 1 }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="equipmentName" label="设备名称" width="160" />
            <el-table-column prop="brand" label="设备品牌" width="160" />
            <el-table-column prop="typeName" label="设备类别" width="160" />
            <el-table-column prop="model" label="设备规格型号" width="160" />
            <el-table-column prop="supplierName" label="设备供应商" width="160" show-overflow-tooltip />
            <el-table-column prop="unitName" label="设备单位" width="160" />
            <el-table-column label="采购单价（元）" width="160">
              <template slot-scope="scope">
                <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.price'" :rules="rules.fileType">
                  <el-input-number style="width:100%;margin-top: 20px;" :min="0" :controls="false"
                    @input.native="onInput0_100" v-model="scope.row.price" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="是/否计量设备" width="160">
              <template slot-scope="{row}">
                <div>{{ ['是', '否'][row.meterageFlag] }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="meterageNum" label="计量编号" width="160">
              <template slot-scope="{row}">
                <div> {{ row.meterageNum || '-' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="操作" fixed="right" width="220">
              <template slot-scope="scope">
                <el-button size="small" icon="el-icon-delete" type="danger" @click="handledelete(scope.$index)">删除
                </el-button>
                <el-button size="small" type="primary" icon="el-icon-view" @click="handleSelectImage(scope.row.image)">
                  图片
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div v-if="ruleForm.purchaseType == 1">
        <!-- ---------------------------------------------------比价采购：物料采购表格----------------------------------------------------------- -->
        <div class="dialog_table">
          <el-table :data="ruleForm.SubmitSelectList" max-height="550px" style="width: 100%" v-if="ruleForm.type == 1">
            <el-table-column label="序号" width="100">
              <template slot-scope="scope">
                <div> {{ scope.$index + 1 }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="materialName" label="物料名称" />
            <el-table-column prop="typeName" label="物料类别" />
            <el-table-column prop="model" label="物料规格型号" show-overflow-tooltip>
              <template slot-scope="{row}">
                <div> {{ row.model || '-' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="物料单位" key="unitName" />
            <el-table-column label="物料类型" key="kind">
              <template slot-scope="{row}">
                <dict-tags :options="SparePartsAndConsumables" :value="row.kind" />
              </template>
            </el-table-column>
            <el-table-column label="采购数量" key="purchaseCount">
              <template slot-scope="scope">
                <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.purchaseCount'"
                  :rules="rules.purchaseCount">
                  <el-input-number style="width:100%;margin-top: 20px;" :min="1" :controls="false"
                    @change="((val) => handleequipmentNameNumber(val, scope.row.materialName))"
                    @input.native="onInput0_100" v-model="scope.row.purchaseCount" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="物料总库存" key="amount">
              <template slot-scope="{row}">
                <div> {{ row.amount || '0' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="操作" width="220" fixed="right">
              <template slot-scope="scope">
                <el-button size="small" icon="el-icon-delete" type="danger"
                  @click="handledeleteconvention(scope.$index, scope.row.materialName)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- ---------------------------------------------------比价采购：设备采购表格----------------------------------------------------------- -->
        <div class="dialog_table">
          <el-table :data="ruleForm.SubmitSelectList" style="width: 100%" max-height="550px" v-if="ruleForm.type == 0">
            <el-table-column label="序号" width="100">
              <template slot-scope="scope">
                <div> {{ scope.$index + 1 }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="equipmentName" label="设备名称" width="160" />
            <el-table-column prop="brand" label="设备品牌" width="160" />
            <el-table-column prop="typeName" label="设备类别" width="160" />
            <el-table-column prop="model" label="设备规格型号" width="160" />
            <el-table-column label="是/否计量设备" width="160">
              <template slot-scope="{row}">
                <div>{{ ['是', '否'][row.meterageFlag] }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="meterageNum" label="计量编号" width="160">
              <template slot-scope="{row}">
                <div> {{ row.meterageNum || '-' }} </div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="采购数量" width="160">
              <template slot-scope="scope">
                <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.purchaseCount'"
                  :rules="rules.purchaseCount">
                  <el-input-number style="width:100%;margin-top: 20px;" :min="1" :controls="false"
                    @change="((val)=>handleequipmentNameNumber(val,scope.row.equipmentName))"
                    @input.native="onInput0_100" v-model="scope.row.purchaseCount" />
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column prop="meterageNum" label="备注" width="160">
              <template slot-scope="{row}">
                <div> {{ row.remark || '-' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="meterageNum" label="设备附件" width="160">
              <template slot-scope="scope">
                <el-link :disabled="!(scope.row.file)" icon="el-icon-document" type="primary" :href="scope.row.file"
                  target="_blank">
                  附件资料</el-link>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="220">
              <template slot-scope="scope">
                <el-button size="small" type="primary" icon="el-icon-view" @click="handleSelectImage(scope.row.image)">
                  图片
                </el-button>
                <el-button size="small" icon="el-icon-delete" type="danger"
                  @click="handledeleteconvention(scope.$index, scope.row.equipmentName)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-divider>供应商比选信息</el-divider>
        <div class="dialog_btn">
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleSubmitSupplier">添加比选供应商</el-button>
        </div>
        <!-- ---------------------------------------------------比价采购：供应商比选信息表格----------------------------------------------------------- -->
        <div class="dialog_table">
          <el-table :data="ruleForm.supplierCompares" max-height="550px" style="width: 100%">
            <el-table-column label="序号" width="100">
              <template slot-scope="scope">
                <div> {{ scope.$index + 1 }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="supplierName" label="供应商名称" min-width="160" />
            <el-table-column v-if="ruleForm.type == 0" prop="equipmentName" label="设备名称" min-width="160" />
            <el-table-column v-if="ruleForm.type == 1" prop="materialName" label="物料名称" min-width="160" />
            <el-table-column prop="addr" label="地址" min-width="160" />
            <el-table-column prop="liaison" label="联系人" min-width="160" />
            <el-table-column prop="phone" label="联系电话" show-overflow-tooltip min-width="160">
              <template slot-scope="{row}">
                <div> {{ row.phone || '-' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="website" label="官网" show-overflow-tooltip min-width="160">
              <template slot-scope="{row}">
                <div> {{ row.website || '-' }} </div>
              </template>
            </el-table-column>
            <el-table-column prop="file" label="附件" min-width="160">
              <template slot-scope="scope">
                <el-link :disabled="!(scope.row.file)" icon="el-icon-document" type="primary" :href="scope.row.file"
                  target="_blank">
                  附件资料</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="报价（单价）" min-width="160">
              <template slot-scope="scope">
                <el-form-item :prop="'supplierCompares.' + scope.$index + '.price'" :rules="rules.price"
                  style="margin-top:18px ;">
                  <el-input-number style="width:100%;" :controls="false" v-model="scope.row.price"
                    @change="((val) => handlePrices(scope.row.supplierName))" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="报价（总价）" min-width="160">
              <template slot-scope="scope">
                <div v-if="sumFlag">{{ '￥' + (totalPricess(scope.row.price, scope.row.purchaseCount, scope.$index) || 0)
                }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="其他说明" min-width="160">
              <template slot-scope="scope">
                <el-form-item :prop="'supplierCompares.' + scope.$index + '.description'" style="margin-top:18px ;">
                  <el-input type="textarea" autosize v-model="scope.row.description" placeholder="请输入其他说明" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template slot-scope="scope">
                <el-button size="small" type="primary" icon="el-icon-view" @click="handleSelectImage(scope.row.image)">
                  图片
                </el-button>
                <el-button size="small" icon="el-icon-delete" type="danger"
                  @click="handledeleterelations(scope.$index, scope.row.supplierName)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- ---------------------------------------------------比价采购：比选结果信息----------------------------------------------------------- -->
        <div class="dialog_table">
          <el-divider>比选结果</el-divider>
          <div style="width:1000px ;">
            <div style="margin:0 0 15px 30px;color: red;font-size: 12px;">注：审核通过后，新服务商将自动加入供应商管理模块中
            </div>
            <el-form-item label="选定服务商" prop="selectSupplierName" style="width: 100%;">
              <el-select style="width: 400px;" v-model="ruleForm.selectSupplierName" placeholder="请选择服务商"
                @change="handletotalPrices">
                <el-option v-for="item in ParentSupplierList" :key="item.supplierName" :label="item.supplierName"
                  :value="item.supplierName">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="选定原因" prop="selectSupplierReason">
              <el-input style="width: 400px;" type="textarea" placeholder="请输入选定原因"
                :autosize="{ minRows: 4, maxRows: 4 }" v-model="ruleForm.selectSupplierReason" maxlength="100"
                show-word-limit />
            </el-form-item>

            <el-form-item label="采购总价" style="width: 100%;">
              <div style="width: 100%;">{{ '￥' + (totalPrices || 0) }}</div>
            </el-form-item>
          </div>
        </div>
      </div>
      <!-- ---------------------------------------------------附件信息----------------------------------------------------------- -->
      <el-divider>附件信息</el-divider>
      <el-form-item label="图片" style="width: 100%;">
        <Image-upload :limit="9" :value='ruleForm.images' @input="handleimagesInput" />
      </el-form-item>
      <el-form-item label="附件" style="width: 100%;">
        <FileUpload v-model="ruleForm.files" :limit="5" :fileSize="50"
          :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
        </FileUpload>
      </el-form-item>
      <!-- ---------------------------------------------------审核信息----------------------------------------------------------- -->
      <el-divider>审核信息</el-divider>
      <div class="rule_form_audit">
        <el-form-item label="审核人" prop="auditVosUser">
          <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="" style="margin-left:120px">
          <span v-for="(tag, index) in tagUserList" :key="index">
            <el-tag closable disable-transitions @close="tagChange(tag, index)">
              <span>{{ tag.name }}</span>
            </el-tag>
            <span style="font-size:28px;position: relative;top: 5px;">
              <template v-if="index !== tagUserList.length - 1">
                <i class="el-icon-caret-right"></i>
              </template>
            </span>
          </span>

        </el-form-item>
        <el-form-item label="抄送人">
          <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <!-- 常规采购组件 -->
    <Purchase ref="purchase_form" @click_create_submit="handleSlectList" :parlist="selectlist" />
    <!-- 比价采购组件 -->
    <Supplier ref="supplier_form" @click_create_submit="handleSlectList" :parlist="selectlist" />
    <!-- 比选供应商组件 -->
    <Compare-suppliers v-if="supplierFlag" @click_close="() => supplierFlag = false"
      @submit_success="handleSubmitSuccess" :parlist="ParentSupplierList" />
    <!-- 图片显示组件 -->
    <template v-if="ImageOpen">
      <Dialog-image :src="imageSrc" />
    </template>
    <!-- ---------------------------------------------------提交及取消【按钮】----------------------------------------------------------- -->
    <div class="form_btn">
      <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      <el-button @click="handleCloseForm">取消</el-button>
    </div>
  </div>
</template>

<script>
import { add, getuserlist, listDetail } from '@/api/purchasing/purchasing'
import Purchase from './purchase.vue'
import Supplier from './supplier.vue'
import CompareSuppliers from './supplier-parent/supplier.vue'
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  title: "", //采购标题
  type: 0, //采购品类（0设备采购 1物料采购）
  purchaseType: 0, //采购品类（0常规采购 1比价采购）
  SubmitSelectList: [],// 采购列表提交总数据展示
  supplierCompares: [],//比选供应商的数据
  desiredDeliveryTime: "", //预期供货时间
  reason: "", //购置理由
  remark: "", //备注
  images: [],//附件信息，图片
  files: '',//附件信息，附件
  selectSupplierName: '',//选定的供应商名称
  selectSupplierReason: '',//选择当前供应商的原因
  auditVosUser: [],// 审核人
  auditVosType: []// 抄送人
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */
function validateFunction (obj, val) {
  let data = Object.assign({}, obj, val)
  const examine = obj.auditVosUser.map(item => {
    return {
      userId: item,
      userType: 0
    }
  })//审核人
  const copy = obj.auditVosType.map(item => {
    return {
      userId: item,
      userType: 1
    }
  })// 抄送人
  if (obj.purchaseType) {
    delete data.auditVosUser
    delete data.auditVosType
    delete data.SubmitSelectList
    if (obj.type) {
      data.purchaseConsumableBases = obj.SubmitSelectList.map(item => {
        return {
          ...item,
          amount: item.purchaseCount
        }
      })
    } else {
      data.purchaseEquipmentBases = obj.SubmitSelectList
    }
    console.log(data);
    data.totalPrices = val
    data.supplierCompares = obj.supplierCompares.map(item => {
      return {
        supplierFrom: item.supplierFrom,  /* 供应商来源（1系统外 2系统内）*/
        supplierName: item.supplierName, /* 供应商名称 */
        address: item.addr, /** 地址 */
        contact: item.liaison, /** 联系人 */
        telephone: item.phone,   /** 联系电话 */
        website: item.website, /** 官网 */
        image: item.image,   /** 图片 */
        file: item.file,    /** 附件 */
        description: item.description, /* 服务商特点描述 */
        remark: item.remark, // 备注信息
        price: item.price, //报价（单价）
        totalPrice: item.totalPrice, //报价（总价）
        materialName: obj.type ? item.materialName : item.equipmentName      //采购物料名称
      }
    })
  } else {
    delete data.supplierCompares
    delete data.selectSupplierReason
    delete data.selectSupplierName
    delete data.SubmitSelectList
    delete data.auditVosUser
    delete data.auditVosType
    if (obj.type) {
      data.purchaseConsumableVos = obj.SubmitSelectList.map(item => {
        return {
          ...item,
          amount: item.overplusAmount
        }
      })
    } else {
      data.purchaseEquipmentVos = obj.SubmitSelectList
    }
  }
  data.images = obj.images.map(item => item.url).join(',')
  data.auditVos = examine.concat(copy)
  console.log(data);
  return data
}
export default {
  name: 'detailedform',
  components: {
    Purchase,
    Supplier,
    CompareSuppliers
  },
  data () {
    return {
      ruleForm: Object.assign({}, ruleForm),
      formFLag: false,
      imageSrc: undefined,//图片预览参数
      ImageOpen: false,
      allUserData: [],//用户信息列表
      supplierFlag: false,//比选服务商弹框开关
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7; //只能选择今天及今天之后的日期
          //return time.getTime() < Date.now() - 8.64e6; //只能选择今天之后的日期，今天的日期也不能选
        }
      },
      ParentSupplierList: [],//用于系统内供应商的数据回显
      selectlist: [],//用于采购品的数据回显
      totalPrices: '',//采购总价
      sumFlag: true,
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        title: [
          { required: true, message: '请输入采购标题', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择采购品类', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        purchaseType: [
          { required: true, message: '请选择采购类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        desiredDeliveryTime: [
          { required: true, message: '请选择供货日期', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        reason: [
          { required: true, message: '请输入购置理由', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        purchaseCount: [
          { required: true, message: '请输入采购数量', trigger: 'blur' }
        ],
        fileNum: [
          { required: true, message: '请输入采购数量', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入报价（单价）', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入其他说明', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        selectSupplierName: { required: true, message: '请选择服务商', trigger: 'change' },
        auditVosUser: { required: true, message: '请选择审核人', trigger: 'change' },
        auditVosType: { required: true, message: '请选择抄送人', trigger: 'change' },
      }
    }
  },
  computed: {
    // 审核人数据转换--------------------------
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  created () {
    this.getlist()
  },
  methods: {
    // 重新申请的回显事件--------------
    handlegetFormlist (id) {
      if (id) {
        this.formFLag = true
        listDetail(id).then(({ data: res }) => {
          console.log(res);
          this.ruleForm.title = res.title;
          this.ruleForm.type = res.type * 1;
          this.ruleForm.desiredDeliveryTime = res.desiredDeliveryTime;
          this.ruleForm.reason = res.reason;
          this.ruleForm.remark = res.remark;
          this.ruleForm.files = res.files
          if (res.images) {
            this.ruleForm.images = res.images.split(',').map(item => {
              return {
                url: item
              }
            })
          }

          this.ruleForm.purchaseType = res.purchaseType * 1;
          if (res.purchaseType == 1) {
            this.ruleForm.selectSupplierName = res.supplierCompare.supplierName
            this.ruleForm.supplierCompares = res.supplierCompares.map(i => {
              return {
                ...i,
                equipmentName: i.materialName,
                materialName: i.materialName,
                addr: i.address,
                liaison: i.contact,
                telephone: i.phone,
              }
            })
            // ------------------------------------比价采购--------------------------------
            if (res.type == 1) {
              // 物料采购
              this.ruleForm.SubmitSelectList = res.purchaseConsumableBases
              for (let j = 0; j < this.ruleForm.supplierCompares.length; j++) {
                for (let i = 0; i < this.ruleForm.SubmitSelectList.length; i++) {
                  const A = this.ruleForm.supplierCompares[j];
                  const B = this.ruleForm.SubmitSelectList[i];
                  if (A.materialName == B.materialName) {
                    this.ruleForm.supplierCompares[j].purchaseCount = B.purchaseCount
                  }
                }
              }
            } else {
              // 设备采购
              this.ruleForm.SubmitSelectList = res.purchaseEquipmentBases
              for (let j = 0; j < this.ruleForm.supplierCompares.length; j++) {
                for (let i = 0; i < this.ruleForm.SubmitSelectList.length; i++) {
                  const A = this.ruleForm.supplierCompares[j];
                  const B = this.ruleForm.SubmitSelectList[i];
                  if (A.materialName == B.equipmentName) {
                    this.ruleForm.supplierCompares[j].purchaseCount = B.purchaseCount
                  }
                }
              }
            }
            this.ParentSupplierList = this.removedup(res.supplierCompares, 'supplierName')
            this.handletotalPrices(res.supplierCompare.supplierName)
            this.ruleForm.selectSupplierReason = res.selectSupplierReason
          } else {
            // -------------------------------------常规采购-------------------------------
            if (res.type == 1) {
              // 物料采购
              this.ruleForm.SubmitSelectList = res.purchaseConsumableVos.map(item => item.consPriceAndAmountVo) || []
            } else {
              // 设备采购
              this.ruleForm.SubmitSelectList = res.purchaseEquipmentVos.map(item => {
                return {
                  ...item.purchaseEquipmentBaseVo,
                  price: item.price
                }
              }) || []
            }
          }
        })
      } else {
        this.formFLag = false
      }
    },
    // ----------添加采购品【按钮】 ------------------
    handleAddPurchase () {
      this.ruleForm.selectSupplierName = ''
      this.totalPrices = ''
      this.selectlist = this.ruleForm.SubmitSelectList
      if (this.ruleForm.purchaseType) {
        // 比价采购，进入Supplier 组件
        this.$refs['supplier_form'].openDialog(this.ruleForm.type)
      } else {
        // 常规采购，进入 Purchase 组件
        this.$refs['purchase_form'].openDialog(this.ruleForm.type)
      }
    },
    async getlist () {
      // 用户列表接口-------------------------
      const userdata = await getuserlist();
      this.allUserData = userdata.data
    },
    // 表单采购类型选择器切换
    handleOptions () {
      this.ruleForm.SubmitSelectList = []
      this.ruleForm.supplierCompares = []
      this.ParentSupplierList = []
      this.selectlist = []
    },
    // 接收子组件勾选后的数据
    handleSlectList (val) {
      console.log(val);
      console.log(this.ParentSupplierList);
      if (this.ruleForm.purchaseType) {
        this.selectlist = val.selectionList
        if (val.type) {
          let arr = val.selectionList.map(item => {
            return {
              ...item,
              purchaseCount: 1
            }
          })
          this.ruleForm.SubmitSelectList.push(...arr)
        } else {
          let array = val.selectionList.map(item => {
            return {
              ...item,
              purchaseCount: 1,
            }
          })
          this.ruleForm.SubmitSelectList.push(...array)
        }
        if (this.ruleForm.supplierCompares.length) {
          console.log(val.selectionList);
          let array = []
          let list = val.selectionList.map(item => {
            return {
              ...item,
              purchaseCount: 1,
            }
          })
          this.ParentSupplierList.forEach(i => {
            list.forEach(j => {
              array.push({
                addr: i.address,
                liaison: i.contact,
                telephone: i.phone,
                ...i,
                ...j,
                price: j.price,
                supplierName: i.supplierName,
              })
            })
          })
          console.log(array);
          this.ruleForm.supplierCompares.push(...array)
        }
      } else {
        const arr = [...this.ruleForm.SubmitSelectList, ...val];
        this.ruleForm.SubmitSelectList = this.removedup(arr, this.ruleForm.type == 0 ? 'equipmentName' : 'materialName').map(item => {
          return {
            ...item,
            purchaseCount: 1
          }
        });
      }
      console.log(this.ruleForm.supplierCompares);
    },
    // fn2 (arr) {
    //   const res = new Map();
    //   return arr.filter(arr => !res.has(arr.consumableBaseId) && res.set(arr.consumableBaseId, arr.consumableBaseId));
    // },

    // 供应商比选信息的单价输入事件
    handlePrices () {
      this.ruleForm.selectSupplierName = ''
      this.totalPrices = ''
    },
    //常规采购采购---采购列表的删除事件
    handledelete (index) {
      this.ruleForm.selectSupplierName = ''
      this.totalPrices = ''
      this.ruleForm.SubmitSelectList.splice(index, 1)
    },
    // 比价采购---设备采购列表和物料采购列表删除事件-------------
    handledeleteconvention (index, indexname) {
      this.ruleForm.selectSupplierName = ''
      this.totalPrices = ''
      this.ruleForm.SubmitSelectList.splice(index, 1)
      let arr = this.ruleForm.supplierCompares
      for (let i = arr.length - 1; i >= 0; i--) {
        if (this.ruleForm.type) {
          if (arr[i].materialName == indexname) {
            this.ruleForm.supplierCompares.splice(i, 1)
            this.ParentSupplierList.splice(i, 1)
          }
        } else {
          if (arr[i].equipmentName == indexname) {
            this.ruleForm.supplierCompares.splice(i, 1)
            this.ParentSupplierList.splice(i, 1)
          }
        }
      }
    },
    // 比价采购---供应商列表删除事件-------------
    handledeleterelations (index, indexname) {
      let arr = this.ruleForm.supplierCompares
      for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i].supplierName == indexname) {
          this.ruleForm.supplierCompares.splice(i, 1)
          this.ParentSupplierList.splice(i, 1)
        }
      }
    },

    // 比选供应商点击事件-----------------------
    handleSubmitSupplier () {
      this.ruleForm.selectSupplierName = ''
      this.totalPrices = ''
      console.log(this.ParentSupplierList);
      if (this.ruleForm.SubmitSelectList.length) {
        this.supplierFlag = true
      } else {
        this.$message({
          message: '请先选择采购品！',
          type: 'warning'
        });
        return
      }
    },

    // 添加比选服务商传上来的数据
    handleSubmitSuccess (val) {
      this.supplierFlag = false
      let array = []
      if (val.faultLevel) {
        // 系统外供应商
        let obj = Object.assign({ supplierFrom: 1 }, val.supplierObj);
        let supplier = [obj]
        supplier.forEach(i => {
          this.ruleForm.SubmitSelectList.forEach(j => {
            array.push({
              ...i,
              ...j,
              supplierName: i.supplierName
            })
          })
        })
        this.ruleForm.supplierCompares.push(...array)
        this.ParentSupplierList = this.removedup(this.ruleForm.supplierCompares, 'supplierName');
      } else {
        // 系统内供应商
        console.log('选择的数据', val.supplierIdList);
        let supplier = []
        supplier = val.supplierIdList.map(item => {
          return {
            ...item,
            supplierFrom: 2
          }
        })
        supplier.forEach(i => {
          this.ruleForm.SubmitSelectList.forEach(j => {
            array.push({
              ...i,
              ...j,
              supplierName: i.supplierName,
              image: i.image
            })
          })
        })
        console.log(array);
        // this.ruleForm.supplierCompares.push(...array)
        this.ruleForm.supplierCompares.push(...array)
        this.ParentSupplierList = this.removedup(this.ruleForm.supplierCompares, 'supplierName');
      }
    },
    handletotalPrices (name) {
      if (!this.ruleForm.selectSupplierName) {
        return
      }
      this.totalPrices = this.ruleForm.supplierCompares.filter(item => item.supplierName == name).map(item => item.totalPrice).reduce((a, b) => a + b).toFixed(2)
    },
    totalPricess (price, total, i) {
      console.log(price, total);
      this.ruleForm.supplierCompares[i].totalPrice = (price || 0) * (total || 0)
      return (price * total).toFixed(2)
    },
    // 审核人删除事件
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    onInput0_100 (e) {
      this.$message.closeAll();
      // 验证是否是纯数字
      let isNumber = /^\d*$/.test(e.target.value);
      // 过滤非数字
      e.target.value = e.target.value.replace(/\D/g, "");
      if (!isNumber || e.target.value < 0) {
        this.$message.warning("只能输入整数");
      }
      e.target.value = (e.target.value >= 0 && e.target.value.match(/^\d*/g)[0]) || null;
    },
    // 表单总提交事件
    handleSubmitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = validateFunction(this.ruleForm, this.totalPrices)
          add(data).then(() => {
            this.$emit('form_submit_click')
            this.handleRemove()
            this.$message.success(this.formFLag ? '重新申请采购成功！' : '新增采购申请成功！');
          })
        } else {
          this.$message.error('提交表单验证信息不通过，请重新输入');
        }
      })
    },
    // 附件的图片事件----- 
    handleimagesInput (val) {
      this.ruleForm.images = val
    },
    // 输入采购数量的输入事件-------------
    handleequipmentNameNumber (value, name) {
      // if (!this.ruleForm.selectSupplierName) {
      //   return
      // }
      this.ruleForm.selectSupplierName = ''
      this.totalPrices = ''
      this.sumFlag = false
      this.ruleForm.supplierCompares.forEach((item, i) => {
        if (this.ruleForm.type) {
          if (item.materialName == name) {
            // this.ruleForm.supplierCompares[i].purchaseCount = value
            this.$set(this.ruleForm.supplierCompares[i], 'purchaseCount', value)
          }
        } else {
          if (item.equipmentName == name) {
            this.$set(this.ruleForm.supplierCompares[i], 'purchaseCount', value)
          }
        }
      })
      this.sumFlag = true
    },
    // 数据重置
    handleRemove () {
      let arr = {
        title: "", //采购标题
        type: 0, //采购品类（0设备采购 1物料采购）
        purchaseType: 0, //采购品类（0常规采购 1比价采购）
        SubmitSelectList: [],// 采购列表提交总数据展示
        supplierCompares: [],//比选供应商的数据
        desiredDeliveryTime: "", //预期供货时间
        reason: "", //购置理由
        remark: "", //备注
        images: [],//附件信息，图片
        files: '',//附件信息，附件
        selectSupplierName: '',//选定的供应商名称
        selectSupplierReason: '',//选择当前供应商的原因
        auditVosUser: [],// 审核人
        auditVosType: []// 抄送人
      }
      this.ruleForm = arr
    },
    // 表单取消事件
    handleCloseForm () {
      this.handleRemove()
      this.$emit('form_submit_click')
    },
    // 查看图片
    handleSelectImage (src) {
      console.log(src);
      this.imageSrc = src
      this.ImageOpen = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog_table {
  margin-top: 20px;
}

.rule_form {
  .el-select {
    width: 400px;
  }

  .el-input {
    width: 400px;
  }
}

/* el-descriptions-item 文字居中 */
::v-deep .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.rule_form_audit {
  width: 26%;
  margin: auto;
}

.dialog_btn {
  margin: 10px 45px;
}



.form_btn {
  width: 42%;
  display: flex;
  justify-content: center;
  margin: 50px auto 20px auto;
}
</style>